package com.chanzany.srb.sms.service.impl;

import com.chanzany.common.exception.Assert;
import com.chanzany.common.exception.BusinessException;
import com.chanzany.common.result.ResponseEnum;
import com.chanzany.srb.sms.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author ChanZany
 * @Date 2021/4/14 19:19
 * @Version 1.0
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void send(String mobile) {
        //生成六位数随机验证码
        String code = getCode();
        //设置redis的key，这里设置为项目名:使用的字段:电话号码
        String redisKey = "srb:sms:code:" + mobile;
        Assert.isNull(redisTemplate.opsForValue().get(redisKey), ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
        try {
            //将这个验证码存入redis中，并设置失效时间为5分钟
            redisTemplate.opsForValue().set(redisKey, code, 300, TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR, e);
        }

    }

    private String getCode() {
        Random random = new Random();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            result.append(random.nextInt(10));
        }
        return result.toString();
    }
}
